<template>
  <ZZDialog class="queryroute" title="路线导航" @close="callbackClose()">
    <el-form style="padding: 10px">
      <el-form-item label="方式">
        <el-select v-model="routeType" placeholder="请选择">
          <el-option v-for="item in routeoptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="起点">
        <div style="padding-right: 10px">{{ startPoint[0] + ',' + startPoint[1] }}</div>
        <el-button @click="drawPoint('start')">选点</el-button>
      </el-form-item>
      <el-form-item label="终点">
        <div style="padding-right: 10px">{{ endPoint[0] + ',' + endPoint[1] }}</div>
        <el-button @click="drawPoint('end')">选点</el-button>
      </el-form-item>
      <el-collapse>
        <el-collapse-item title="路线详情" name="1">
          <div>总距离：{{ allDistance }}</div>
          <div>预计时间：{{ allTime }}</div>
          <div>导航：{{ allText }}</div>
        </el-collapse-item>
      </el-collapse>
    </el-form>
  </ZZDialog>
</template>

<script setup lang="ts">
import { ref, onBeforeMount } from 'vue';
import { useViewer } from '@/stores/viewer';
import ZZDialog from '@/common/ZZDialog.vue';
import startImg from './img/start.png';
import endImg from './img/end.png';

let viewer: any; //场景视图
const routeoptions = [
  { value: 1, label: '步行路线查询' },
  { value: 2, label: '骑行路线查询' },
  { value: 3, label: '驾车路线查询' }
];
const routeType = ref(1);
const startPoint = ref([0, 0]);
const endPoint = ref([0, 0]);
let startMarker: any;
let endMarker: any;
let line: any;
const gaodeRoute = new GaodeRoute();

const allTime = ref('');
const allDistance = ref('');
const allText = ref('');
onBeforeMount(() => {
  viewer = useViewer().viewer;
});
function drawPoint(type: string) {
  viewer.zz.draw.startDraw({
    type: 'billboard',
    style: {
      image: type == 'start' ? startImg : endImg
    },
    success: (entity: any) => {
      const cartesian = entity.position.getValue();
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      const jd = Number(Cesium.Math.toDegrees(cartographic.longitude).toFixed(6));
      const wd = Number(Cesium.Math.toDegrees(cartographic.latitude).toFixed(6));
      if (type == 'start') {
        startPoint.value = [jd, wd];
        if (startMarker) {
          viewer.zz.draw.deleteEntity(entity);
          startMarker.position = cartesian;
        } else {
          startMarker = entity;
        }
      } else {
        endPoint.value = [jd, wd];
        if (endMarker) {
          viewer.zz.draw.deleteEntity(entity);
          endMarker.position = cartesian;
        } else {
          endMarker = entity;
        }
      }
      queryRoute();
    }
  });
}
function queryRoute() {
  if (!startPoint.value || !endPoint.value) {
    return;
  }
  if (line) {
    viewer.entities.remove(line);
    line = null;
  }
  gaodeRoute.query({
    type: routeType.value,
    points: [startPoint.value, endPoint.value],
    success: (data: any) => {
      line = addLine(data.paths[0]);
      showResult(data);
    },
    error: (msg: any) => {
      console.log('msg: ', msg);
    }
  });
}
function showResult(data: any) {
  allTime.value = formatTime(data.paths[0].allDuration);
  allDistance.value = (Number(data.paths[0].allDistance) / 1000).toFixed(2) + '公里';

  let dhHtml = '';
  for (let i = 0; i < data.paths[0].steps.length; i++) {
    const item = data.paths[0].steps[i];
    dhHtml += item.instruction + '；';
  }
  dhHtml = dhHtml.slice(0, -1) + '。';
  allText.value = dhHtml;
}
function addLine(arg: any) {
  const lnglats = arg.points;
  if (!lnglats || lnglats.length < 1) return;

  const positions = zz3d.pointconvert.lonlats2cartesians(lnglats);

  const time = arg.allDuration;
  const distance = arg.allDistance;
  const html = '<div>总距离：' + distance + '<br/>所需时间：' + time + '</div>';

  return viewer.entities.add({
    polyline: {
      positions: positions,
      clampToGround: true,
      material: Cesium.Color.AQUA.withAlpha(0.8),
      width: 5
    },
    popup: html
  });
}
function formatTime(seconds: number): string {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);

  let result = '';
  if (hours > 0) {
    result += `${hours}小时`;
  }
  if (minutes > 0) {
    result += `${minutes}分`;
  }
  return result;
}

const callbackClose = function () {
  if (startMarker) {
    viewer.zz.draw.deleteEntity(startMarker);
    startMarker = null;
  }
  if (endMarker) {
    viewer.zz.draw.deleteEntity(endMarker);
    endMarker = null;
  }
  if (line) {
    viewer.entities.remove(line);
    line = null;
  }
};
</script>
<style scoped lang="less">
.queryroute {
  position: absolute;
  top: 100px;
  right: 200px;
  height: 280px;
  width: 300px;
  overflow-y: auto;
}
</style>
